using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Agriculture.Api.Read.Application.Command;
using Agriculture.Domain;
using Dapper;
using MediatR;
using Microsoft.Extensions.Configuration;
using MySql.Data.MySqlClient;

namespace Agriculture.Api.Read.Application.Handler
{
    /// <summary>
    /// 问诊单查询处理器
    /// </summary>
    public class ConsultationOrderQueryHandler : IRequestHandler<ConsultationOrderQuery, ConsultationOrderQueryResult>
    {
        private readonly IConfiguration _configuration;

        public ConsultationOrderQueryHandler(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        public async Task<ConsultationOrderQueryResult> Handle(ConsultationOrderQuery request, CancellationToken cancellationToken)
        {
            var result = new ConsultationOrderQueryResult();
            string connectionString = _configuration.GetConnectionString("DefaultConnection");

            using (var connection = new MySqlConnection(connectionString))
            {
                // 构建查询条件
                var conditions = new List<string>();
                var parameters = new DynamicParameters();

                conditions.Add("co.IsDeleted = 0");

                // 患者姓名或手机号查询
                if (!string.IsNullOrEmpty(request.PatientSearch))
                {
                    conditions.Add("(p.Name LIKE @PatientSearch OR p.Phone LIKE @PatientSearch)");
                    parameters.Add("@PatientSearch", $"%{request.PatientSearch}%");
                }

                // 问诊状态查询
                if (request.ConsultationStatus.HasValue && request.ConsultationStatus.Value > 0)
                {
                    // 1：审核通过，2：未通过
                    conditions.Add("co.ConsultationStatus = @ConsultationStatus");
                    parameters.Add("@ConsultationStatus", request.ConsultationStatus.Value);
                }

                // 问诊方式查询
                if (request.ConsultationType.HasValue && request.ConsultationType.Value > 0)
                {
                    // 1：图文问诊，2：视频问诊，3：电话问诊
                    conditions.Add("co.ConsultationType = @ConsultationType");
                    parameters.Add("@ConsultationType", request.ConsultationType.Value);
                }

                // 问诊来源查询
                if (request.ConsultationSource.HasValue && request.ConsultationSource.Value > 0)
                {
                    // 1：视频问诊，2：图文问诊，3：电话问诊，4：极速图文，5：极速电话，6：复诊开药
                    conditions.Add("co.ConsultationSource = @ConsultationSource");
                    parameters.Add("@ConsultationSource", request.ConsultationSource.Value);
                }

                // 时间范围查询
                if (request.StartTime.HasValue)
                {
                    conditions.Add("co.SubmitTime >= @StartTime");
                    parameters.Add("@StartTime", request.StartTime.Value);
                }

                if (request.EndTime.HasValue)
                {
                    conditions.Add("co.SubmitTime <= @EndTime");
                    parameters.Add("@EndTime", request.EndTime.Value.AddDays(1).AddSeconds(-1)); // 结束时间为当天23:59:59
                }

                // 订单状态查询
                if (request.OrderStatus.HasValue && request.OrderStatus.Value > 0)
                {
                    // 1：待支付，2：进行中，3：已完成，4：已取消，5：已退诊
                    int statusCode = 0;
                    switch (request.OrderStatus.Value)
                    {
                        case 1:
                            statusCode = 1; // 待支付状态码
                            break;
                        case 2:
                            statusCode = 2; // 进行中状态码
                            break;
                        case 3:
                            statusCode = 3; // 已完成状态码
                            break;
                        case 4:
                            statusCode = 4; // 已取消状态码
                            break;
                        case 5:
                            statusCode = 5; // 已退诊状态码
                            break;
                    }

                    conditions.Add("co.Status = @OrderStatus");
                    parameters.Add("@OrderStatus", statusCode);
                }

                // 构建WHERE子句
                var whereClause = conditions.Count > 0 ? $" WHERE {string.Join(" AND ", conditions)}" : string.Empty;

                // 统计总记录数
                var countSql = @"
                    SELECT COUNT(1) 
                    FROM consultationordermodel co 
                    LEFT JOIN patientmodel p ON co.PatientId = p.Id
                    LEFT JOIN doctormodel d ON co.DoctorId = d.Id" + whereClause;
                
                var totalCount = await connection.ExecuteScalarAsync<int>(countSql, parameters);

                // 计算总页数
                int totalPages = (int)Math.Ceiling(totalCount / (double)request.PageSize);

                // 分页查询数据
                var offset = (request.PageIndex - 1) * request.PageSize;
                var querySql = @"
                    SELECT co.SubmitTime, p.Name AS Patient, d.Department, 
                           d.Name AS Doctor, co.ConsultationType, co.ConsultationSource, 
                           co.ConsultationFee, co.Status AS OrderStatusCode, co.OrderNo
                    FROM consultationordermodel co
                    LEFT JOIN patientmodel p ON co.PatientId = p.Id
                    LEFT JOIN doctormodel d ON co.DoctorId = d.Id
                    " + whereClause + @"
                    ORDER BY co.SubmitTime DESC
                    LIMIT @Offset, @PageSize";

                parameters.Add("@Offset", offset);
                parameters.Add("@PageSize", request.PageSize);

                var orders = await connection.QueryAsync<dynamic>(querySql, parameters);

                // 转换为DTO
                var dtoList = orders.Select(o => new ConsultationOrderDto
                {
                    SubmitTime = o.SubmitTime,
                    Patient = o.Patient,
                    Department = o.Department,
                    Doctor = o.Doctor,
                    ConsultationType = ConvertConsultationType(o.ConsultationType),
                    ConsultationSource = ConvertConsultationSource(o.ConsultationSource),
                    ConsultationFee = o.ConsultationFee,
                    OrderStatus = ConvertOrderStatus(o.OrderStatusCode),
                    OrderNo = o.OrderNo
                }).ToList();

                // 构建结果
                result.TotalCount = totalCount;
                result.TotalPages = totalPages;
                result.CurrentPage = request.PageIndex;
                result.ConsultationOrders = dtoList;
            }

            return result;
        }

        /// <summary>
        /// 转换问诊方式码为文本
        /// </summary>
        private string ConvertConsultationType(int type)
        {
            switch (type)
            {
                case 1:
                    return "图文问诊";
                case 2:
                    return "视频问诊";
                case 3:
                    return "电话问诊";
                default:
                    return "未知";
            }
        }

        /// <summary>
        /// 转换问诊来源码为文本
        /// </summary>
        private string ConvertConsultationSource(int source)
        {
            switch (source)
            {
                case 1:
                    return "视频问诊";
                case 2:
                    return "图文问诊";
                case 3:
                    return "电话问诊";
                case 4:
                    return "极速图文";
                case 5:
                    return "极速电话";
                case 6:
                    return "复诊开药";
                default:
                    return "未知";
            }
        }

        /// <summary>
        /// 转换订单状态码为状态文本
        /// </summary>
        private string ConvertOrderStatus(int status)
        {
            switch (status)
            {
                case 1:
                    return "待支付";
                case 2:
                    return "进行中";
                case 3:
                    return "已完成";
                case 4:
                    return "已取消";
                case 5:
                    return "已退诊";
                default:
                    return "未知";
            }
        }
    }
} 